/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jili.ubert.server.priceserver;

import com.jili.ubert.code.server2client.Price;
import com.jili.ubert.netty.MsgEntity;
import io.netty.channel.Channel;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author ChengJiLi
 */
public class DeliveryBucket {

    private final ConcurrentHashMap<String, List<Channel>> listenHandlerMap;

    public DeliveryBucket() {
        listenHandlerMap = new ConcurrentHashMap<>(2 ^ 50);
    }

    public DeliveryBucket(int contains) {
        listenHandlerMap = new ConcurrentHashMap<>(contains);
    }

    public void Register(String id, Channel hander) {
        if (this.listenHandlerMap.containsKey(id)) {
            this.listenHandlerMap.get(id).add(hander);
        } else {
            List<Channel> handlerList = new ArrayList<>();
            handlerList.add(hander);
            this.listenHandlerMap.put(id, handlerList);
        }
    }

    public void OnDealListen(Price data) {
        String id = data.getMaketCode().concat(data.getObj());
        if (listenHandlerMap.containsKey(id)) {
            MsgEntity msg = new MsgEntity();
            try {
                byte[] dd = Price.EnCode(data);
                listenHandlerMap.get(id).stream().forEach((Channel handler) -> {
                    msg.SendMsg(handler, 3, 0, dd);
                });
            } catch (IOException ex) {
                Logger.getLogger(DeliveryBucket.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void CancelRegister(String id) {
        if (this.listenHandlerMap.containsKey(id)) {
            listenHandlerMap.remove(id);
        }
    }

    public void CancelRegister(Channel hander) {
        listenHandlerMap.keySet().stream().forEach((key) -> {
            List<Channel> handlerList = listenHandlerMap.get(key);
            if (handlerList.contains(hander)) {
                handlerList.remove(hander);
                if (handlerList.isEmpty()) {
                    listenHandlerMap.remove(key);
                }
            }
        });
    }

    public void CancelRegister(String id, Channel hander) {
        if (this.listenHandlerMap.containsKey(id)) {
            if (listenHandlerMap.get(id).size() == 1 && listenHandlerMap.get(id).contains(hander)) {
                listenHandlerMap.remove(id);
            } else {
                listenHandlerMap.get(id).remove(hander);
            }
        }
    }
}
